//
//  ZKRefreshControl.swift
//  Weibo
//
//  Created by 郑克哥哥 on 2017/7/31.
//  Copyright © 2017年 郑克哥哥. All rights reserved.
//

import UIKit

//下拉刷新的三种状态
enum RefreshControlType {
    
    //下拉刷新
    case normal
    //松手刷新
    case pulling
    //正在刷新
    case refresh
    
}

//自定义下拉刷新控件的高度
let RefreshControlHeight: CGFloat = 50

//自定义下拉刷新
class ZKRefreshControl: UIControl {
    
    //默认状态
    var refreshType:  RefreshControlType = .normal{
        didSet{
            
            switch refreshType {
            case .normal:
                //下拉刷新
                //1.显示箭头
                pullRefreshView.isHidden = false
                //2.停止刷新动画
                refurbishView.stopAnimating()
                //3.箭头重置
                UIView.animate(withDuration: 0.25, animations: {
                    self.pullRefreshView.transform = CGAffineTransform.identity
                }, completion: { (_) in
                    //oldValue:表示上一次保存的数据
                    if oldValue == .refresh{
                        //重置停留位置
                        UIView.animate(withDuration: 0.25, animations: {
                            self.currentView!.contentInset.top -= RefreshControlHeight
                        })
                    }
                    
                })
                //4.文字改变
                label.text = "下拉刷新"
            case .pulling:
                //松手就刷新
                //1.箭头变化
                UIView.animate(withDuration: 0.25, animations: { 
                    self.pullRefreshView.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
                })
                //2.文字改变
                label.text = "释放更新"
            case .refresh:
                //正在刷新
                //1.隐藏箭头
                pullRefreshView.isHidden = true
                //2.开启刷新动画
                refurbishView.startAnimating()
                //3.文字改变
                label.text = "加载中..."
                UIView.animate(withDuration: 0.25, animations: { 
                    //设置停留位置
                    self.currentView!.contentInset.top += RefreshControlHeight
                }, completion: { (_) in
                    //发送刷新事件
                    self.sendActions(for: .valueChanged)
                })
                
           
            }
        }
    }
    
    //记录当前刷新的父视图
    var currentView: UIScrollView?
    
    
    //加载控件
    //箭头图片
    private lazy var pullRefreshView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    //文字
    private lazy var label:UILabel = {
        
        let lab = UILabel()
        
        lab.font = UIFont.systemFont(ofSize: 12)
        lab.text = "下拉刷新"
        lab.textColor = UIColor.darkGray
        
        return lab
    }()
    
    //刷新动画
    private lazy var refurbishView:UIActivityIndicatorView = {
    
        let indicato = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
        return indicato
    }()
    
        

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //添加控件设置约束
    private func setupUI(){
        
        backgroundColor = UIColor.white
        addSubview(pullRefreshView)
        addSubview(label)
        addSubview(refurbishView)
        
        //手写代码自动布局
        pullRefreshView.translatesAutoresizingMaskIntoConstraints = false
        label.translatesAutoresizingMaskIntoConstraints = false
        refurbishView.translatesAutoresizingMaskIntoConstraints = false

        //设置约束,(设置中心点)
        //箭头约束
        addConstraint(NSLayoutConstraint(item: pullRefreshView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: pullRefreshView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
        //箭头右边文字约束
        addConstraint(NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: pullRefreshView, attribute: .trailing, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: pullRefreshView, attribute: .centerY, multiplier: 1, constant: 0))
        //刷新动画
        addConstraint(NSLayoutConstraint(item: refurbishView, attribute: .centerX, relatedBy: .equal, toItem: pullRefreshView, attribute: .centerX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: refurbishView, attribute: .centerY, relatedBy: .equal, toItem: pullRefreshView, attribute: .centerY, multiplier: 1, constant: 0))
    }
    
    //MARK: -------将要添加到父视图上-------
    override func willMove(toSuperview newSuperview: UIView?) {
        //获取父视图,使用KVO来监听tableView的滚动
        guard let scrollView = newSuperview as? UIScrollView else{
            //表示不是滚动的视图,不需要监听其滚动
            return
        }
         self.frame = CGRect(x: 0, y: 0 - RefreshControlHeight, width: scrollView.frame.size.width, height: RefreshControlHeight)
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
        //记录当前视图
        currentView = scrollView
    }
    
    //KVO的监听方法
    /*
     keyPath:监听对象的属性
     object:监听的对象
     change:对象改变的信息
     context:上下文参数
     */
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        let contentOffsetY = currentView!.contentOffset.y
        print(contentOffsetY)
        if currentView!.isDragging {
            //拖动临界点,contentInset.top:内容显示的位置距离顶部的距离
            let limitMaxY = -((currentView?.contentInset.top)! + RefreshControlHeight)
            if contentOffsetY < limitMaxY && refreshType == .normal{
                //进入pulling状态
                refreshType = .pulling
                print("pulling")
            }else if refreshType == .pulling && contentOffsetY >= limitMaxY {
                //进入normal状态
                refreshType = .normal
                print("normal")
            }
        }else{
            //松手
            print("松手")
            //1.松手 2. 当前状态是pulling才能进入refresh
            if refreshType == .pulling {
                refreshType = .refresh
                print("refresh")
            }
        }
    }
    
    //结束刷新
    func endRefreshing() {
        
        //把刷新改成默认状态
        refreshType = .normal
        
        
        
    }
    
    //移除KVO的监听
    deinit {
        currentView?.removeObserver(self, forKeyPath: "contentOffset")
    }

}
